using System;
using System.Collections.Generic;
using Unity.VisualScripting.Dependencies.NCalc;
using UnityEngine;
using UnityEngine.AI;

public class AIReaderSource : IInputSource
{
    public Vector3 Forward { get; private set; }
    private Transform self;
    private Vector3 spawnPos;                 // 出生点（无巡逻点时回这里）
    private Transform transform;                 // 追击目标（玩家）
    private float sightRadius = 6f;          // 发现半径
    private float attackRange = 1f;
    private float attackCooldown = 0f;   // 攻击CD
    private float attackCdTimer = 0f;

    //接口类
    public bool MoveInput { get; private set; }
    public bool ShiftMoveInput { get; private set; }
    public bool IsJumping { get; private set; }

    public bool leftClick { get; private set; }
    public bool rightClick { get; private set; }
    public bool rightHoldClick { get; private set; }
    public bool die { get; private set; }
    public AIReaderSource(GameObject characterGameObject, float AttackCooldown)
    {
        self = characterGameObject.transform;
        spawnPos = self.position;
        // Forward = Vector3.zero;
        // die = false;
        // agent.enabled = false;
        // agent.updateRotation = false; // 禁用NavMeshAgent的自动旋转
        attackCdTimer = 0; // 设置初始攻击冷却
        attackCooldown = AttackCooldown; // 设置间断攻击冷却
    }

    public void onUpdate()
    {
        PursuitPlayer();

    }

    GameObject AttackTarget()
    {
        // 使用 Physics2D.OverlapCircle 检测圆形范围内是否有带有 "Player" 标签的对象
        Collider2D playerCollider = Physics2D.OverlapCircle(transform.position, 10, LayerMask.GetMask("Player"));
        if (playerCollider != null && playerCollider.CompareTag("Player"))
        {
            return playerCollider.gameObject;
        }
        return null;
    }

    private void PursuitPlayer()
    {
        if (AttackTarget() == null)
        {
            MoveInput = false;
            //后续可以添加进入巡逻状态之类的
            return;
        }

        // 每帧递减冷却时间
        if (attackCdTimer > 0f)
            attackCdTimer -= Time.deltaTime;
        MoveInput = true;
        leftClick = !MoveInput;

        // 如果来到玩家附近
        bool reached = (AttackTarget().transform.position - self.position).sqrMagnitude
                   <= attackRange * attackRange;

        if (reached)
        {
            MoveInput = false;

            // 冷却结束 → 触发一次攻击
            if (attackCdTimer <= 0f)
            {
                leftClick = true;
                attackCdTimer = attackCooldown;
            }
            else
            {
                leftClick = false; // 冷却中，保持不攻击
            }
        }
    }

    //外用接口 控制是否开始移动
    public void StartMove()
    {
        if (AttackTarget() == null) return;


    }

    //外用接口 控制是否停止移动
    public void StopMove()
    {
        MoveInput = false;

    }


    public AIReaderSource SetTransform(Transform t) { transform = t; return this; }


}
